package com.deyuanyun.pic.web.timedtask;

import com.deyuanyun.pic.common.util.AppcenterClassFinder;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.MyClassUtil;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xu on 2016/1/26.
 * 定时任务入口
 */
@Component
public class MainTask {
    static Logger logger = Logger.getLogger(MainTask.class);


    public static Map<String, Date> taskRunTime = new HashMap<String, Date>();//每增加一组任务。该值加1
    //定为两分钟检查一次定时任务
    @Scheduled(cron="0 0/2 *  * * ?")
    public void taskMainMethod(){
        if (!TaskConfigUtil.isTaskServer()){
            return;
        }


        int n=TaskPool.threadPoolTaskExecutor.getActiveCount();
        if (n>20){
            logger.error("队列中还有任务太多，等待下一次执行...........");
            return;
        }

        List<Class<? extends Scheduledable>> classList = AppcenterClassFinder.getInstance().findSubClass(Scheduledable.class);
        List<? extends Scheduledable> scheduledableList = MyClassUtil.newInstance(classList);
        for (Scheduledable s : scheduledableList){
            Integer ii=s.crTimeMinu();
            if(ii==null||ii==-1||ii==0){continue;}
            Date lastTime=taskRunTime.get(s.getScheduledType());//上一次执行的时间
            if(lastTime!=null){
                int c= DateUtil.minuteBetween(lastTime,new Date());//现在时间与上次时间相差多少分钟
                if(c<ii){
                    continue;
                }
            }else {
                taskRunTime.put(s.getScheduledType(),new Date());
            }


            Integer threadNum=s.threadCount();
            if (threadNum==null||threadNum==0){
                threadNum=1;
            }
            for (int ti=0;ti<threadNum;ti++){
                try {
                    Scheduledable ss1=s.getClass().newInstance();
                    Map map= Maps.newHashMap();
                    map.put("threadNum",ti);
                    ss1.setMark(map);
                    TaskPool.threadPoolTaskExecutor.execute(ss1);
                } catch (Exception e) {
                    logger.error(s.getScheduledType() + "新建实例失败!", e);
                }
            }
        }


    }
}
